package com.wangyf.thread.c_010_lock;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 查看ReentrantLock写法，也要等 m1 的lock释放 m2才会执行
 * @author wangyf
 * @date 2021/1/3 18:05
 */
public class T {
    private Lock lock = new ReentrantLock();

    void m1() {
        try {
            lock.lock();
            for (int i = 0; i < 10; i++) {
                TimeUnit.SECONDS.sleep(1);
                System.out.println(i);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }
    void m2() {
        try {
            lock.lock();
            System.out.println("m2");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }

    public static void main(String[] args) throws InterruptedException {
        T t = new T();
        new Thread(t::m1).start();
        TimeUnit.SECONDS.sleep(2);
        new Thread(t::m2).start();
    }
}
